package com.example.demo.realm;


import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.service.impl.UserServiceImpl;

/**
 * @author Henry.Y
 * @date 2019-05-24
 */
public class UserRealm extends AuthorizingRealm{

	private UserService userService= new UserServiceImpl();
	
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection){
		String username= (String)principalCollection.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo= new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(userService.findRoles(username));
		authorizationInfo.setStringPermissions(userService.findPermissions(username));
		return authorizationInfo;
	}
	
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)throws AuthenticationException{
		String username= (String)token.getPrincipal();
		User user= userService.findUserByUsername(username);
		if(null==user){
			throw new UnknownAccountException();
		}
		
		if(Boolean.TRUE.equals(user.getLocked())){
			throw new LockedAccountException();
		}
		SimpleAuthenticationInfo authenticationInfo= new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),ByteSource.Util.bytes(user.getCredentialSalt()),getName());
		return authenticationInfo;
		
	}
	
	/**
	 * 以下方法在第11章时被使用
	 */
	
	public void clearCachedAuthorizationInfo(PrincipalCollection principals){
		super.clearCachedAuthorizationInfo(principals);;
	}
	
	public void clearCachedAuthenticationInfo(PrincipalCollection principals){
		super.clearCachedAuthenticationInfo(principals);
	}
	
	public void clearCache(PrincipalCollection principals){
		super.clearCache(principals);
	}
	
	public void clearAllAuthorizationInfo(){
		getAuthorizationCache().clear();
	}
	
	public void clearAllAuthenticationInfo(){
		getAuthenticationCache().clear();
	}
	
	public void clearAllCache(){
		clearAllAuthorizationInfo();
		clearAllAuthenticationInfo();
	}
}